"""阿里云api"""
from Tea.exceptions import TeaException
from alibabacloud_alidns20150109 import models as alidns_20150109_models
from alibabacloud_alidns20150109.client import Client as Alidns20150109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from application import settings


class AliBabaCloudSample:
    def __init__(self, access_key_id=None, access_key_secret=None,
                 endpoint='alidns.cn-zhangjiakou.aliyuncs.com'):
        self.access_key_id = access_key_id or settings.ACCESS_KEY_ID
        self.access_key_secret = access_key_secret or settings.ACCESS_KEY_SECRET
        self.endpoint = endpoint
        config = open_api_models.Config(
            # 您的AccessKey ID,
            access_key_id=self.access_key_id,
            # 您的AccessKey Secret,
            access_key_secret=self.access_key_secret
        )
        # 访问的域名
        config.endpoint = self.endpoint
        self.create_client = Alidns20150109Client(config)

    def sms_create_client(self) -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(access_key_id=self.access_key_id, access_key_secret=self.access_key_secret)
        # 访问的域名
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    def describe_domains(self, page_size=40, page_number=1, domains=[]):
        """
        查询所有域名地址
        :param page_size:
        :param page_number:
        :param domains:
        :return:
        """
        describe_domains_request = alidns_20150109_models.DescribeDomainsRequest(page_number=page_number,
                                                                                 page_size=page_size)
        # 复制代码运行请自行打印 API 的返回值
        response = self.create_client.describe_domains(describe_domains_request)
        domains.extend([ele.domain_name for ele in response.body.domains.domain])
        total_count = response.body.total_count
        if total_count > page_size * page_number:
            self.describe_domains(page_size=page_size, page_number=page_number + 1, domains=domains)
        return domains

    def add_domain_record_request(self, domain_name, rr, value=None, type='A'):
        """
        根据传入参数添加解析记录
        :param domain_name: 域名名称
        :param rr: 主机记录
        :param value: 记录值
        :param type: 解析记录类型
        :return:
        """
        add_domain_record_request = alidns_20150109_models.AddDomainRecordRequest(
            domain_name=domain_name,
            rr=rr,
            type=type,
            value=value or settings.DOMAIN_IP
        )
        # 复制代码运行请自行打印 API 的返回值
        try:
            response = self.create_client.add_domain_record(add_domain_record_request)
            if response.body.record_id:
                return True
        except TeaException as e:
            print(e.message)
        return False

    def delete_sub_domain_records(self, domain_name, rr, type='A'):
        """
        根据传入参数删除主机记录对应的解析记录
        :param domain_name:
        :param rr:
        :param type:
        :return:
        """
        delete_sub_domain_records_request = alidns_20150109_models.DeleteSubDomainRecordsRequest(
            domain_name=domain_name, rr=rr, type=type)
        try:
            res = self.create_client.delete_sub_domain_records(delete_sub_domain_records_request)
            if res.body.total_count != '0':
                return True
        except TeaException as e:
            print(e.message)
        return False

    def is_exist_domains(self, domain):
        domains = self.describe_domains()
        return domain in domains

    def send_sms(self, sign_name, template_code, phone_numbers, template_param) -> bool:
        client = self.sms_create_client()
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=sign_name,
            template_code=template_code,
            phone_numbers=phone_numbers,
            template_param=template_param
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            client.send_sms_with_options(send_sms_request, runtime)
            return True
        except Exception as error:
            # 如有需要，请打印 error
            print(error)
            UtilClient.assert_as_string(error.message)
            return False


if __name__ == '__main__':
    access_key_id = ""
    access_key_secret = ""
    sample = AliBabaCloudSample(access_key_id=access_key_id, access_key_secret=access_key_secret)
